﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Base;
using Lamex.Common;
using Lamex.Interface;
using Lamex.Interface.ISystem;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace Lamex.Library
{
    public partial class frmBaseDataForm : frmBaseChild
    {
        /// <summary>
        /// 当显示修改明细页时,首先获取焦点的编辑框.
        /// </summary>
        public string IsEdit = "";
        public string KeysName = "";
        protected Control _ActiveEditor;

        /// <summary>
        /// 关键字段输入框,新增时不可修改
        /// </summary>
        protected Control _KeyEditor;

        /// <summary>
        /// 主表的数据表格对象,必须由派生类指定表格类型。
        /// 因Dev GridControl组件不可继承所以子类窗体Load的时候需要赋值.
        /// </summary>
        protected ISummaryView _SummaryView;

        /// <summary>
        /// 数据编辑页的主容器
        /// 因继承问题,需要在子类窗体Load的时候需要赋值
        /// </summary>
        protected Control _DetailGroupControl;
        public frmBaseDataForm()
        {
            InitializeComponent();
        }
        protected virtual void InitializeForm() //此方法由基类的Load事件调用
        {
            //try { this.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
            //this.SetViewMode();//预设为数据查看模式
            //this.SetButtonAuthority();//设置按钮权限

            //无操作状态下不可输入数据

        }
        public virtual void InitChangeLanguage2()
        {

        }
        /// <summary>
        /// 给表格绑定数据
        /// </summary>
        /// <param name="dataSource"></param>
        protected void DoBindingSummaryGrid(DataTable dataSource)
        {
            if (_SummaryView != null)
            {
                _SummaryView.DataSource = null;
                _SummaryView.DataSource = dataSource;
            }
        }
        /// <summary>
        /// 初始化数据窗体的按钮
        /// </summary>
        public override void InitButtons()
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
        }
        /// <summary>
        /// 数据操作状态
        /// </summary>
        protected UpdateType _UpdateType = UpdateType.None;
        /// <summary>
        /// 是否修改了数据
        /// </summary>
        public bool IsDataChanged
        {
            get { return this.IsAddOrEditMode; }
        }
        /// <summary>
        /// 是否新增/修改模式
        /// </summary>
        public bool IsAddOrEditMode
        {
            get { return (_UpdateType == UpdateType.Add) || (_UpdateType == UpdateType.Modify); }
        }
        protected virtual string GetStateName()
        {
            if (UpdateType.Add == _UpdateType) return "(新增)";
            else if (UpdateType.Modify == _UpdateType) return "(修改)";
            else return "(查询)";
        }
        /// <summary>
        /// 是否新增/修改模式
        /// </summary>
        //public bool IsAddOrEditMode
        //{
        //    get { return (_UpdateType == UpdateType.Add) || (_UpdateType == UpdateType.Modify); }
        //}
        /// <summary>
        /// 是否数据发生改变
        /// </summary>
        public bool DataChanged
        {
            get { return this.IsAddOrEditMode; }
        }
        /// <summary>
        /// 是否允许用户操作数据
        /// </summary>
        protected bool _AllowDataOperate = true;
        /// <summary>
        /// 是否允许用户操作数据
        /// </summary>
        public bool AllowDataOperate
        {
            get { return _AllowDataOperate; }
            set
            {
                _AllowDataOperate = value;
                //this.SetViewMode();
            }
        }
       
        

        /// <summary>
        /// 数据操作状态
        /// </summary>
        public UpdateType UpdateType { get { return _UpdateType; } }

        public virtual string UpdateTypeName
        {
            get
            {
                if (UpdateType.Add == _UpdateType) return "(新增模式)";
                else if (UpdateType.Modify == _UpdateType) return "(修改模式)";
                else return "(查看模式)";
            }
        }

        /// <summary>        
        ///设置为编辑模式
        ///数据操作两种状态.1：数据修改状态 2：查看数据状态 
        /// </summary>
        //protected virtual void SetEditMode()
        //{
        //    _buttons.GetButtonByName("btnView").Enable = true;
        //    _buttons.GetButtonByName("btnAdd").Enable = true;
        //    _buttons.GetButtonByName("btnDelete").Enable = true;
        //    _buttons.GetButtonByName("btnEdit").Enable = true;
        //    _buttons.GetButtonByName("btnPrint").Enable = true;
        //    _buttons.GetButtonByName("btnPreview").Enable = true;
        //    _buttons.GetButtonByName("btnSave").Enable = true;
        //    _buttons.GetButtonByName("btnCancel").Enable = true;
        //}
        /// <summary>        
        ///设置为查看模式
        ///数据操作两种状态.1：数据修改状态 2：查看数据状态 
        /// </summary>
        //protected virtual void SetViewMode()
        //{
        //    _buttons.GetButtonByName("btnView").Enable = _AllowDataOperate;
        //    _buttons.GetButtonByName("btnAdd").Enable = _AllowDataOperate && ButtonAuthorized(ButtonAuthority.ADD);
        //    _buttons.GetButtonByName("btnDelete").Enable = _AllowDataOperate && ButtonAuthorized(ButtonAuthority.DELETE);
        //    _buttons.GetButtonByName("btnEdit").Enable = _AllowDataOperate && ButtonAuthorized(ButtonAuthority.EDIT);
        //    _buttons.GetButtonByName("btnPrint").Enable = ButtonAuthorized(ButtonAuthority.PRINT);
        //    _buttons.GetButtonByName("btnPreview").Enable = ButtonAuthorized(ButtonAuthority.PREVIEW);
        //    _buttons.GetButtonByName("btnSave").Enable = true;
        //    _buttons.GetButtonByName("btnCancel").Enable = true;
        //}
        /// <summary>
        /// 查看选中记录的数据
        /// </summary>
        /// <param name="sender"></param>
        public virtual void DoViewContent(IButtonInfo sender)
        {
            this.ButtonStateChanged(_UpdateType);
        }
        public override void DoReturn(IButtonInfo sender)
        {
            xtraTabPage1.PageEnabled = true;
            xtraTabPage2.PageEnabled = false;
            IsEdit = "";
            base.DoReturn(sender);
        }
        public override void DoCancel(IButtonInfo sender)
        {
            //this.Close();
            base.DoCancel(sender);
        }
        public virtual void DoClose(IButtonInfo sender)
        {
            this.Close();
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        public override void DoAdd(IButtonInfo sender)
        {
            xtraTabPage1.PageEnabled = false;
            xtraTabPage2.PageEnabled = true;
            xtraTabPage2.PageVisible = true;
            if(Loginer.CurrentUser.ChangeLanguage==0)
            {
                IsEdit = "Add";
                xtraTabPage2.Tag = "Add";
            }
            else
            {
                IsEdit = "Add";
                xtraTabPage2.Tag = "Add";
            }
            
            base.DoAdd(sender);
            base.DoAdd(sender);
        }
        public override void DoEdit(IButtonInfo sender)
        {
            xtraTabPage1.PageEnabled = false;
            xtraTabPage2.PageEnabled = true;
            xtraTabPage2.PageVisible = true;
            if (Loginer.CurrentUser.ChangeLanguage == 0)
            {
                IsEdit = "Edit";
                xtraTabPage2.Tag = "Edit";
            }
            else
            {
                IsEdit = "Edit";
                xtraTabPage2.Tag = "Edit";
            }
            
            base.DoEdit(sender);
        }
        
        ///// <summary>
        ///// 新增记录
        ///// </summary>
        ///// <param name="sender"></param>
        //public virtual void DoAdd(IButtonInfo sender)
        //{
        //    this._UpdateType = UpdateType.Add;
        //    this.SetEditMode();
        //    this.ButtonStateChanged(_UpdateType);
        //}

        ///// <summary>
        ///// 修改数据
        ///// </summary>
        ///// <param name="sender"></param>
        //public virtual void DoEdit(IButtonInfo sender)
        //{
        //    this._UpdateType = UpdateType.Modify;
        //    this.SetEditMode();
        //    this.ButtonStateChanged(_UpdateType);
        //}

        ///// <summary>
        ///// 取消新增或修改
        ///// </summary>
        ///// <param name="sender"></param>
        //public virtual void DoCancel(IButtonInfo sender)
        //{
        //    try
        //    {
        //        this._UpdateType = UpdateType.None;
        //        this.SetViewMode();
        //        this.ButtonStateChanged(_UpdateType);

        //        if (_UpdateType == UpdateType.Add)
        //            this.ShowSummaryPage(true);
        //        else if (_SummaryView.RowCount > 0)
        //            this.DoViewContent(sender);
        //    }
        //    catch (Exception e)
        //    {
        //        MessageBox.Show(e.Message);
        //    }
        //}

        ///// <summary>
        ///// 保存数据
        ///// </summary>
        ///// <param name="sender"></param>
        //public virtual void DoSave(IButtonInfo sender)
        //{
        //    this._UpdateType = UpdateType.None;
        //    this.SetViewMode();
        //    this.ShowDetailPage(false);
        //    this.ButtonStateChanged(_UpdateType);
        //}
        ///// <summary>
        ///// 删除记录
        ///// </summary>
        ///// <param name="sender"></param>
        //public virtual void DoDelete(IButtonInfo sender) { }
        /// <summary>
        /// 按钮状态发生变化
        /// </summary>        
        protected virtual void ButtonStateChanged(UpdateType currentState)
        {
            //
        }
        /// <summary>
        /// 显示明细页
        /// </summary>
        protected void ShowDetailPage(bool disableSummaryPage)
        {
            try
            {
                this.SuspendLayout();
                this.tpDetail.PageEnabled = true;
                tcBusiness.SelectedTabPage = this.tpDetail;
                tpSummary.PageEnabled = !disableSummaryPage;
                FocusEditor(); //第一个编辑框获得焦点.
                this.ResumeLayout();
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }
        /// <summary>
        /// 第一个编辑控件设置焦点.
        /// </summary>
        protected void FocusEditor()
        {
            if (_ActiveEditor != null)
            {
                if (_ActiveEditor.CanFocus)
                    _ActiveEditor.Focus();
                else
                    this.SelectNextControl(_ActiveEditor, true, false, true, true);
            }
        }
        /// <summary>
        /// 显示主表页
        /// </summary>
        protected void ShowSummaryPage(bool disableDetailPage)
        {
            try
            {
                this.tpSummary.PageEnabled = true;
                tcBusiness.SelectedTabPage = this.tpSummary;
                tpDetail.PageEnabled = !disableDetailPage;
                if (_SummaryView != null) _SummaryView.SetFocus();
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }
        /// <summary>
        /// 表格是否有数据
        /// </summary>
        /// <returns></returns>
        public virtual bool HasData()
        {
            if (_SummaryView != null)
                return _SummaryView.RowCount > 0;
            else
                return false;
        }
        /// <summary>
        /// 双击表格事件
        /// </summary>
        protected virtual void OnGridViewDoubleClick(object sender, EventArgs e)
        {
            try
            {
                if (SystemConfig.CurrentConfig == null) return;
                if (!this.HasData()) return;

                IButtonInfo btn = _buttons.GetButtonByName("btnEdit");

                //双击表格进入修改状态
                if (SystemConfig.CurrentConfig.DoubleClickIntoEditMode)
                {
                    if (this.ButtonAuthorized(ButtonAuthority.EDIT)) //当前用户有修改权限
                    {
                        this.DoEdit(btn); //调用修改方法
                        return;
                    }
                }
                else //只能查看
                {
                    this.DoViewContent(btn);
                    SetDetailEditorsAccessable(_DetailGroupControl, false);
                }
            }
            catch { }
        }
        /// <summary>
        ///获取当前光标所在的资料行. 
        /// </summary>
        protected DataRow GetFocusedRow()
        {
            if (_SummaryView.FocusedRowHandle < 0)
                return null;
            else
            {
                if (_SummaryView.DataSource is DataTable)
                    return GetDataRow(_SummaryView.FocusedRowHandle);
                else
                    return null;
            }
        }
        /// <summary>
        ///获取指定的资料行
        /// </summary>
        protected DataRow GetDataRow(int rowIndex)
        {
            if (rowIndex < 0) return null;
            if (SummaryTable != null) return SummaryTable.Rows[rowIndex];
            return null;
        }
        /// <summary>
        /// 获取Summary表的数据源.         
        /// </summary>
        protected DataTable SummaryTable
        {
            get
            {
                if (_SummaryView == null) return null;
                return (DataTable)_SummaryView.DataSource;
            }
        }
        /// <summary>
        /// 控制明细页面上的控件可被编辑.
        /// </summary>
        protected virtual void SetDetailEditorsAccessable(Control panel, bool value)
        {
            if (panel == null) return;

            for (int i = 0; i < panel.Controls.Count; i++)
            {
                SetControlAccessable(panel.Controls[i], value);
            }

            controlNavigatorSummary.Enabled = !value;
        }
        /// <summary>
        /// 设置控件状态.ReadOnly or Enable = false/true
        /// </summary>
        protected void SetControlAccessable(Control control, bool value)
        {
            try
            {
                if (control is Label) return;
                if (control is ControlNavigator) return;
                if (control is UserControl) return;

                if (control.Controls.Count > 0)
                {
                    foreach (Control c in control.Controls)
                        SetControlAccessable(c, value);
                }

                System.Type type = control.GetType();
                PropertyInfo[] infos = type.GetProperties();
                foreach (PropertyInfo info in infos)
                {
                    if (info.Name == "ReadOnly")//ReadOnly
                    {
                        info.SetValue(control, !value, null);
                        return;
                    }
                    if (info.Name == "Properties")//Properties.ReadOnly
                    {
                        object o = info.GetValue(control, null);
                        if (o is RepositoryItem)
                        {
                            ((RepositoryItem)o).ReadOnly = !value;
                        }
                        //解决日期控件和ButtonEdit在浏览状态下也能按button的问题
                        if ((o is RepositoryItemButtonEdit) && (((RepositoryItemButtonEdit)o).Buttons.Count > 0))
                            ((RepositoryItemButtonEdit)o).Buttons[0].Enabled = value;
                        if ((o is RepositoryItemDateEdit) && (((RepositoryItemDateEdit)o).Buttons.Count > 0))
                            ((RepositoryItemDateEdit)o).Buttons[0].Enabled = value;
                        return;
                    }
                    if (info.Name == "Views")//OptionsBehavior.Editable
                    {
                        object o = info.GetValue(control, null);
                        if (null == o) return;
                        foreach (object view in (GridControlViewCollection)o)
                        {
                            if (view is ColumnView)
                                ((ColumnView)view).OptionsBehavior.Editable = value;
                        }
                        return;
                    }

                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }
        /// <summary>
        /// 关窗体中...
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmBaseDataForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //if (this.DataChanged)
                //e.Cancel = !MessageBox.Show("您修改了数据没有保存，确定要退出吗?","",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
        }
    }
}
